package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vos.LoginVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    // @Autowired
    // private PasswordEncoder passwordEncoder;

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) throws Exception {
        //1. 获取手机号和密码
        String phone = dto.getPhone();
        String password = dto.getPassword();

        //2. 判断手机号或密码是否为空,为空返回0生成的jwt
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)){
            String token = AppJwtUtil.getToken(0L);
            return ResponseResult.okResult(token);
        }

        //2. 根据手机号查询用户
        ApUser apUser = this.lambdaQuery().eq(ApUser::getPhone, phone).one();
        if (apUser == null){
            throw new Exception("手机号或密码错误");
        }

        //3. 校验是否禁用
        if (apUser.getStatus().equals(1)){
            throw new Exception("用户被冻结");
        }

        //4. 校验密码
        // if (!passwordEncoder.matches(password,apUser.getPassword())){
        //     throw new Exception("用户名或密码错误");
        // }
        boolean checkpw = BCrypt.checkpw(password, apUser.getPassword());

        if (!BCrypt.checkpw(password,apUser.getPassword())){
            throw new Exception("用户名或密码错误");
        }

        //5. 生成token
        String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));

        //6. 封装返回数据
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("id",apUser.getId());
        userMap.put("name",apUser.getName());
        userMap.put("phone",apUser.getPhone());
        LoginVo loginVo = new LoginVo();
        loginVo.setUser(userMap);
        loginVo.setToken(token);

        return ResponseResult.okResult(loginVo);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
